package services

import (
    "encoding/json"
    "fmt"
    "time"
    "volux/utils"
)

type LogService struct {
    etcdClient  *utils.EtcdClient
    logLevel    string
    maxSize     int64
    retention   time.Duration
}

type LogEntry struct {
    Timestamp time.Time              `json:"timestamp"`
    Level     string                 `json:"level"`
    Source    string                 `json:"source"`
    Message   string                 `json:"message"`
    Fields    map[string]interface{} `json:"fields,omitempty"`
}

func NewLogService(etcdClient *utils.EtcdClient) *LogService {
    return &LogService{
        etcdClient:  etcdClient,
        logLevel:    "info",
        maxSize:     100 * 1024 * 1024, // 100MB
        retention:   7 * 24 * time.Hour, // 7 days
    }
}

func (ls *LogService) Log(entry LogEntry) error {
    key := fmt.Sprintf("/logs/%s/%d", entry.Source, entry.Timestamp.UnixNano())
    data, err := json.Marshal(entry)
    if err != nil {
        return err
    }

    // 使用TTL存储日志
    return ls.etcdClient.PutWithTTL(key, string(data), int64(ls.retention.Seconds()))
}

func (ls *LogService) Query(source string, start, end time.Time, level string) ([]LogEntry, error) {
    prefix := fmt.Sprintf("/logs/%s/", source)
    events, err := ls.etcdClient.GetWithPrefix(prefix)
    if err != nil {
        return nil, err
    }

    var entries []LogEntry
    for _, event := range events {
        var entry LogEntry
        if err := json.Unmarshal([]byte(event.Kv.Value), &entry); err != nil {
            continue
        }

        if entry.Timestamp.After(start) && entry.Timestamp.Before(end) &&
           (level == "" || entry.Level == level) {
            entries = append(entries, entry)
        }
    }

    return entries, nil
}

func (ls *LogService) SetLogLevel(level string) {
    ls.logLevel = level
}

func (ls *LogService) GetLogLevel() string {
    return ls.logLevel
}

func (ls *LogService) SetRetention(duration time.Duration) {
    ls.retention = duration
}
